package fr.greta.centre.dao;

import java.sql.*;
import java.util.ArrayList;

import javax.naming.NamingException;

import fr.greta.centre.metier.Cursus;
import fr.greta.centre.metier.UE;


public class CursusDAOImpl implements CursusDAO {

	Statement st;




	@Override
	public int save(Cursus c) {
		int i=0;
		try {
			st = Bd.getConnect().createStatement();
			String s = "INSERT INTO `centre_formation`.`cursus` (`libelle`) VALUES ('"+c.getLibelle()+"')";
			System.out.println(s);
			st.executeUpdate(s);

			String ss = "SELECT MAX( id_cursus ) AS LastID FROM cursus";
			ResultSet r = st.executeQuery(ss);
			r.next();
			i = r.getInt(1);
			st.getConnection().close();
		} catch (SQLException e) {	System.out.println(e.getMessage());	}

		System.out.println("insert ok"+" "+i);
		c.setIdCursus(i);		
		return i;
	}


	public boolean delete(int idCursus) {

		try {
			st = Bd.getConnect().createStatement();
			String s = "DELETE FROM `centre_formation`.`cursus` WHERE `cursus`.`id_cursus` = " + idCursus;
			System.out.println(s);
			st.execute(s);
			st.getConnection().close();
			return true;
		} catch (SQLException e) { System.out.println(e.getMessage());

		}

		return false;
	}


	public Cursus findByKey(int idCursus) {
		Cursus unCursus =null;
		try {
			st = Bd.getConnect().createStatement();
			String s = "SELECT * FROM `centre_formation`.`cursus` WHERE `cursus`.`id_cursus` = " +idCursus ;
			System.out.println(s);
			st.execute(s);
			ResultSet r = st.executeQuery(s);
			r.next();
			java.util.List<UE> lesUE = new UEDAOImpl().findByIdCursus(idCursus);
			unCursus = new Cursus(lesUE, idCursus, r.getString("libelle"));
			st.getConnection().close();

		} catch (SQLException e) {System.out.println(e.getMessage());
		return null;
		}

		return unCursus;
	}



	public ArrayList<Cursus> findAll() {

		return null;
	}



	@Override
	public Cursus findByIdUE(int idUE) throws SQLException {
		Cursus curs = new Cursus();

		try {
			st = Bd.getConnect().createStatement();
			String sql = "SELECT * FROM `centre_formation`.`ue` WHERE `cursus`.`id_cursus` = " +curs.getIdCursus() ;
			System.out.println(sql);
			st.execute(sql);
			ResultSet r = st.executeQuery(sql);
			r.next();
			st.getConnection().close();
		}catch (SQLException e) {System.out.println(e.getMessage());

		}

		return null;
	}

}
